package com.bjpowernode.mvc.controller;



import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.bjpowernode.common.CommonUtil;
import com.bjpowernode.common.consts.Keys;
import com.bjpowernode.common.enums.Code;
import com.bjpowernode.db.domain.HeaderImage;
import com.bjpowernode.db.domain.User;
import com.bjpowernode.db.result.UserAccountResult;
import com.bjpowernode.mvc.model.dto.user.TokenUserDTO;
import com.bjpowernode.mvc.model.param.RealNameParam;
import com.bjpowernode.mvc.model.param.UserParam;
import com.bjpowernode.mvc.model.response.Response;
import com.bjpowernode.mvc.model.vo.user.UserAccountResultVO;
import com.bjpowernode.mvc.service.inter.HeaderImageService;
import com.bjpowernode.mvc.service.inter.SmsService;
import com.bjpowernode.mvc.service.inter.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/*@CrossOrigin*/
@RestController
public class UserController {

    @Resource
    private SmsService smsService;

    @Resource
    private UserService userService;

    @Resource
    private HeaderImageService headerImageService;

    @Value("${dfs.http.url}")
    private String DFS_HTTP_URL = "";


    //注册新用户
    @PostMapping(value = "/user/register")
    public Response registerUser(@RequestBody @Validated UserParam param) {
        //判断短信验证码是否有效
        Response response = Response.FAIL();

        //验证请求参数,BeanValidator 这个规范进行注解


        //判断短信验证码是否有效
        String key = Keys.SMS_REG_CODE + param.getPhone();
        boolean check = smsService.checkSmsCode(key, param.getCode());
        if (check) { ///
            //有效,执行逻辑
            int result = userService.registerUser(param.getPhone(), param.getSecret());

            response = Response.BUILD(CommonUtil.convert(result));
        } else {
            response = Response.FAIL(Code.SMS_CODE_INVALID);
        }
        return response;

    }


    //登录,获取token
    @PostMapping(value = "/user/access/token")
    public Response getAccessToken(@RequestBody @Validated UserParam userParam, HttpServletRequest request) {
        Response response = Response.FAIL(Code.SMS_CODE_INVALID);
        //验证短信验证码
        String key = Keys.SMS_LOGIN_CODE + userParam.getPhone();
        boolean checkSmsCode = smsService.checkSmsCode(key, userParam.getCode());
        if (checkSmsCode) {
            //登录.访问用户.
            User user = userService.userLogin(userParam.getPhone(), userParam.getSecret(), request.getRemoteHost());

            if (user != null) {
                //登录成功.使用UUID表示token
                String token = userService.createToken();

                //存储token到redis
                TokenUserDTO tokenUserDTO = new TokenUserDTO();
                tokenUserDTO.setId(user.getId());
                tokenUserDTO.setName(user.getName());
                tokenUserDTO.setPhone(user.getPhone());
                tokenUserDTO.setToken(token);

                boolean save = userService.saveTokenRedis(tokenUserDTO);
                if (save) {
                    response = Response.ok(tokenUserDTO);
                } else {
                    response = Response.FAIL(Code.USER_LOGIN_ERR);
                }
            } else {
                response = Response.FAIL(Code.USER_LOGIN_ERR);
            }
        }
        return response;


    }


    //实名认证.
    @PostMapping(value = "/user/realname")
    public Response userRealName(@RequestBody @Validated RealNameParam realNameParam,
                                 @RequestHeader("Uid") Integer userid) {
        User user = userService.queryById(userid);
        //检查是否做个实名认证
        if (user != null) {
            if (StrUtil.isNotEmpty(user.getName())) {
                //做过实名认证.
                return Response.FAIL(Code.REALNAME_NOT_DOUBLE);
            } else {
                //进行实名认证.
                boolean realname = userService.hashRealname(userid, realNameParam.getName(), realNameParam.getIdCard());
                if (realname) {
                    return Response.ok(realNameParam.getName());
                } else {
                    return Response.FAIL(Code.REALNAME_ERR);
                }
            }
        } else {
            return Response.FAIL(Code.USER_NOT_EXSITS);
        }


    }


    //查询用户基本信息.
    @GetMapping(value = "/user/info")
    public Response userInfo(@RequestHeader("uid") Integer userId) {
        Response response = Response.FAIL();
        UserAccountResult userAccountResult = userService.queryUserAccountInfo(userId);
        if (userAccountResult != null) {

            //查询用户的头像
            HeaderImage headerImage = headerImageService.queryUserId(userId);
            if (headerImage != null) {
                String url = DFS_HTTP_URL + headerImage.getGroupName() + "/" + headerImage.getFileId();
                userAccountResult.setHeaderImage(url);
            }

            //转vo
            response = Response.ok(BeanUtil.copyProperties(userAccountResult, UserAccountResultVO.class));
        }
        return response;
    }


    //退出登录.
    @GetMapping("/user/logout")
    public Response logout(@RequestHeader("Authorization") String authorization) {
        if (StrUtil.isNotBlank(authorization) && authorization.contains("Bearer")) {
            String token = authorization.substring(7);
            String key = Keys.TOKEN_ACCESS + token.toUpperCase();
            boolean remove = userService.removeLoginToken(key);


            if (remove) {
                return Response.ok();
            }
        }
        return Response.FAIL();
    }


}